import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import api from '@/utils/api'

export const useBackgroundTaskStore = defineStore('backgroundTask', () => {
  // 任务列表（支持多个后台任务）
  const tasks = ref([])
  
  // 轮询定时器
  const pollTimers = ref({})
  
  // 添加任务
  const addTask = (task) => {
    const taskData = {
      id: task.taskId,
      type: task.type, // 'jar-upload' 或 'job-operation'
      taskId: task.taskId,
      files: task.files || [], // 文件列表
      progress: {
        current: 0,
        total: task.files?.length || 0
      },
      status: 'running', // 'running', 'completed', 'failed', 'cancelled'
      completed: false,
      startTime: Date.now(),
      endTime: null,
      results: []
    }
    
    tasks.value.push(taskData)
    
    // 保存到 localStorage
    saveToLocalStorage()
    
    // 开始轮询
    startPolling(taskData)
    
    return taskData
  }
  
  // 开始轮询任务状态
  const startPolling = (task) => {
    if (pollTimers.value[task.id]) {
      return // 已经在轮询了
    }
    
    const poll = async () => {
      try {
        let response
        if (task.type === 'jar-upload') {
          response = await api.get(`/jars/task/${task.taskId}`)
        } else if (task.type === 'job-operation') {
          response = await api.get(`/jobs/batch-task/${task.taskId}`)
        }
        
        if (!response.data.success) {
          throw new Error(response.data.error || '获取任务状态失败')
        }
        
        const taskData = response.data.data
        
        // 更新任务进度
        updateTaskProgress(task.id, {
          current: taskData.current || 0,
          total: taskData.total || task.progress.total,
          results: taskData.results || []
        })
        
        // 检查任务是否完成
        if (taskData.status === 'completed' || taskData.status === 'failed' || taskData.status === 'cancelled') {
          completeTask(task.id, taskData.status, taskData)
        }
      } catch (error) {
        console.error('[BackgroundTask] 轮询任务状态失败:', error)
      }
    }
    
    // 立即执行一次
    poll()
    
    // 每秒轮询一次
    pollTimers.value[task.id] = setInterval(poll, 1000)
  }
  
  // 停止轮询
  const stopPolling = (taskId) => {
    if (pollTimers.value[taskId]) {
      clearInterval(pollTimers.value[taskId])
      delete pollTimers.value[taskId]
    }
  }
  
  // 更新任务进度
  const updateTaskProgress = (taskId, progress) => {
    const task = tasks.value.find(t => t.id === taskId)
    if (task) {
      task.progress = {
        current: progress.current,
        total: progress.total
      }
      task.results = progress.results || []
      
      // 保存到 localStorage
      saveToLocalStorage()
    }
  }
  
  // 完成任务
  const completeTask = (taskId, status, taskData) => {
    const task = tasks.value.find(t => t.id === taskId)
    if (!task) return
    
    task.status = status
    task.completed = true
    task.endTime = Date.now()
    
    // 停止轮询
    stopPolling(taskId)
    
    // 保存到 localStorage
    saveToLocalStorage()
    
    // 显示全局通知
    showCompletionNotification(task, taskData)
  }
  
  // 显示完成通知
  const showCompletionNotification = (task, taskData) => {
    const duration = Math.round((task.endTime - task.startTime) / 1000)
    
    if (task.status === 'completed') {
      ElMessage({
        message: `${getTaskTypeName(task.type)}已完成！成功: ${taskData.success_count || 0}, 失败: ${taskData.failed_count || 0}，耗时: ${duration}秒`,
        type: 'success',
        duration: 5000,
        showClose: true
      })
    } else if (task.status === 'failed') {
      ElMessage({
        message: `${getTaskTypeName(task.type)}失败: ${taskData.error || '未知错误'}`,
        type: 'error',
        duration: 5000,
        showClose: true
      })
    } else if (task.status === 'cancelled') {
      ElMessage({
        message: `${getTaskTypeName(task.type)}已取消。成功: ${taskData.success_count || 0}, 失败: ${taskData.failed_count || 0}`,
        type: 'warning',
        duration: 5000,
        showClose: true
      })
    }
  }
  
  // 获取任务类型名称
  const getTaskTypeName = (type) => {
    const names = {
      'jar-upload': 'JAR包上传',
      'job-operation': '作业批量操作'
    }
    return names[type] || '任务'
  }
  
  // 取消任务
  const cancelTask = async (taskId) => {
    const task = tasks.value.find(t => t.id === taskId)
    if (!task) return
    
    try {
      let response
      if (task.type === 'jar-upload') {
        response = await api.post(`/jars/task/${task.taskId}/cancel`)
      } else if (task.type === 'job-operation') {
        response = await api.post(`/jobs/batch-task/${task.taskId}/cancel`)
      }
      
      if (response.data.success) {
        ElMessage.success('任务已取消')
        task.status = 'cancelled'
        task.completed = true
        task.endTime = Date.now()
        stopPolling(taskId)
        saveToLocalStorage()
      }
    } catch (error) {
      console.error('[BackgroundTask] 取消任务失败:', error)
      ElMessage.error('取消任务失败')
    }
  }
  
  // 移除任务
  const removeTask = (taskId) => {
    const index = tasks.value.findIndex(t => t.id === taskId)
    if (index !== -1) {
      stopPolling(taskId)
      tasks.value.splice(index, 1)
      saveToLocalStorage()
    }
  }
  
  // 清除已完成的任务
  const clearCompletedTasks = () => {
    tasks.value = tasks.value.filter(task => {
      if (task.completed) {
        stopPolling(task.id)
        return false
      }
      return true
    })
    saveToLocalStorage()
  }
  
  // 保存到 localStorage
  const saveToLocalStorage = () => {
    const data = tasks.value.map(task => ({
      id: task.id,
      type: task.type,
      taskId: task.taskId,
      files: task.files,
      progress: task.progress,
      status: task.status,
      completed: task.completed,
      startTime: task.startTime,
      endTime: task.endTime,
      results: task.results
    }))
    localStorage.setItem('backgroundTasks', JSON.stringify(data))
  }
  
  // 从 localStorage 恢复
  const restoreFromLocalStorage = () => {
    try {
      const data = localStorage.getItem('backgroundTasks')
      if (data) {
        const savedTasks = JSON.parse(data)
        const now = Date.now()
        
        // 只恢复24小时内的任务
        savedTasks.forEach(taskData => {
          if (now - taskData.startTime < 24 * 60 * 60 * 1000) {
            tasks.value.push(taskData)
            
            // 如果任务未完成，重新开始轮询
            if (!taskData.completed) {
              startPolling(taskData)
            }
          }
        })
      }
    } catch (error) {
      console.error('[BackgroundTask] 恢复任务失败:', error)
    }
  }
  
  // 计算属性：运行中的任务数量
  const runningTasksCount = computed(() => {
    return tasks.value.filter(t => !t.completed).length
  })
  
  // 计算属性：是否有运行中的任务
  const hasRunningTasks = computed(() => {
    return runningTasksCount.value > 0
  })
  
  // 获取特定类型的任务
  const getTasksByType = (type) => {
    return tasks.value.filter(t => t.type === type)
  }
  
  // 获取任务
  const getTask = (taskId) => {
    return tasks.value.find(t => t.id === taskId)
  }
  
  return {
    tasks,
    runningTasksCount,
    hasRunningTasks,
    addTask,
    updateTaskProgress,
    completeTask,
    cancelTask,
    removeTask,
    clearCompletedTasks,
    getTasksByType,
    getTask,
    restoreFromLocalStorage,
    startPolling,
    stopPolling
  }
})

